import store from '../store'
import config from '../config'
import enpt from './encrypt.js'

uni.getProvider({
  service: 'oauth',
  success(res) {
    store.commit('config/SET_SYSTEM_PROVIDER', res.provider[0])
  },
})

const comHeader = {
  'content-type': 'application/x-www-form-urlencoded',
  'eshimin-version': '1.0.0',
  platform: 4,
  channel: 4,
  cityCode: config.cityCode,
  cookie: 'TGT=' + store.state?.user?.TGT,
}
const comData = {
  requestVersion: ' ',
}
const error = {
  code: -1,
  message: '抱歉，网络开小差了',
}
// 列表公钥变量
let SH_RsaPublicKey = ''
let SH_CreateTime = ''
let SH_ExpireTime = 0

// 新账号公钥变量
let xzh_RsaPublicKey = ''
let xzh_CreateTime = ''
let xzh_ExpireTime = ''

switch (store.state?.config?.provider) {
  case 'weixin':
    comHeader.platform = 4
    comHeader.channel = 4
    break
  case 'alipay':
    comHeader.platform = 3
    comHeader.channel = 3
    break
  case 'baidu':
    comHeader.platform = 5
    comHeader.channel = 5
    break
}

const request: EncryptRequest = {
  getRsaKey: () => '',
  encryption: async () => false,
  unencryption: async () => false,
  getLoginRsaKey: async () => Promise.reject(),
  loginRequest: async () => Promise.reject(),
  getTGTRsaKey: async () => Promise.reject(),
}
/**
 * banner公钥
 * @param {*} data
 * @param {*} header
 */
request.getRsaKey = async (data = '', header = {}) => {
  const time = new Date().getTime() + 600000
  if (SH_RsaPublicKey && SH_ExpireTime > time) {
    return SH_RsaPublicKey
  }
  const params = {
    url: `${config.uni_app_web_api_url}/service-converge-consumer/rsaKey`,
    method: 'POST',
    data: data,
    header: header,
  }
  return new Promise((resolve, reject) => {
    uni.request({
      ...(params as UniApp.RequestOptions),
      success(res) {
        const result = res.data as ResponseOptions['data']
        if (result.code == 200 && result.data) {
          SH_RsaPublicKey = result.data.rsaPublicKey
          SH_CreateTime = result.data.createTime
          SH_ExpireTime = result.data.expireTime
          resolve(SH_RsaPublicKey)
        } else {
          resolve('')
        }
      },
      fail(rej) {
        resolve('')
      },
    })
  })
}
/**
 *接口加密
 * @param {*} Url 地址
 * @param {*} type 类型，1.表示解密后需要再次解压，2.表示解密后不需要解压
 * @param {*} newparams 接口调用所需参数
 */
request.encryption = async (url, type, newparams) => {
  let data = {
    ...newparams,
    ...comData,
  }
  let header = {
    ...comHeader,
  }
  const publicKey = await request.getRsaKey()
  if (!publicKey) {
    return false
  }
  const params = {
    url: config.uni_app_web_api_url + url,
    method: 'POST',
    data: enpt.AESRSAencrypt(JSON.stringify(data), publicKey),
    header: header,
  }
  return new Promise((resolve, reject) => {
    uni.request({
      ...(params as UniApp.RequestOptions),
      success(res) {
        const result = <ResponseOptions['data']>res.data
        if (result?.code == 200 && result.data) {
          if (type == 1) {
            //解密后，还需要再次解压
            let data = enpt.RSAdecrypt(result.data)
            let serverList = JSON.parse(data).data.serverList
            let lists = enpt.unzip(serverList)
            resolve(JSON.parse(lists))
          } else {
            //解密后不需要解压
            let data = enpt.RSAdecrypt(result.data)
            let serverList = JSON.parse(data).data
            resolve(serverList)
          }
        } else {
          resolve(result)
        }
      },
      fail(rej) {
        reject(error)
      },
    })
  })
}
//不加密
request.unencryption = (url, method, newparams) => {
  let data = {
    ...newparams,
    ...comData,
  }
  let header = {
    ...comHeader,
  }
  const params = {
    url: config.uni_app_web_api_url + url,
    method: method,
    data: data,
    header: header,
  }
  return new Promise((resolve, reject) => {
    uni.request({
      ...(params as unknown as UniApp.RequestOptions),
      success(res) {
        const result = res.data as ResponseOptions['data']
        if (result.code == 200 && result.data) {
          let response = result.data.data
          resolve(response)
        } else {
          resolve(result)
        }
      },
      fail(rej) {
        reject(error)
      },
    })
  })
}

/**
 * 登录获取公钥
 */
request.getLoginRsaKey = async () => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${config.three_host}/hang/generate`,
      method: 'GET',
      success(res) {
        const result = res.data as ResponseOptions['data']
        if (result.code == 200 && result.data) {
          resolve(result.data)
        } else {
          resolve('')
        }
      },
      fail(rej) {
        resolve('')
      },
    })
  })
}

// 登录接口封装
request.loginRequest = async (newheader, signUri, url, method, data) => {
  let LoginRsaKeyResult = await request.getLoginRsaKey()
  if (!LoginRsaKeyResult) {
    return { code: 90001, message: '获取公钥失败' }
  }
  let timeStamp: string | number = new Date().getTime()
  timeStamp = String(timeStamp)

  let sign = JSON.stringify({
    timeStamp: timeStamp,
    uri: signUri,
    nonce: enpt.nonce,
  })
  // console.log("enpt.nonce", enpt.nonce)
  sign = enpt.cryptomd5(sign)
  let header = {
    'Content-Type': 'multipart/form-data',
    timeStamp: timeStamp,
    uri: signUri,
    nonce: enpt.nonce,
    sign: sign,
    hversion: '2.1',
    platform: 4,
    channel: 4,
    cityCode: config.cityCode,
    ...newheader,
  }

  const UrlParams = AESRSAencrypt(data, LoginRsaKeyResult.public_key)

  let params = {
    url: `${config.three_host}${url}?key=${UrlParams.key}&data=${UrlParams.data}&expire_time=${LoginRsaKeyResult.expire_time}`,
    method: method,
    header: header,
  }
  return new Promise((resolve, reject) => {
    uni.request({
      ...params,
      success(res) {
        const result = res.data as ResponseOptions['data']
        if (result.code == 200 && result.data) {
          let data = enpt.RSAdecrypt(result.data)

          resolve(JSON.parse(data))
        } else {
          resolve(result)
        }
      },
      fail(rej) {
        reject(error)
      },
    })
  })
}

/**
 * TGT获取公钥
 */
request.getTGTRsaKey = async () => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${config.uni_app_web_api_url}/auth/rsa/keygen`,
      method: 'GET',
      success(res) {
        const result = res.data as ResponseOptions['data']
        if (result.code == 200 && result.data) {
          resolve(result.data)
        } else {
          resolve('')
        }
      },
      fail(rej) {
        resolve('')
      },
    })
  })
}

// AES RSA 加密
const AESRSAencrypt = (secretDate: any, public_key: string) => {
  let UrlParams = {
    data: enpt.AESRSAencrypt(JSON.stringify(secretDate), public_key).data,
    key: enpt.AESRSAencrypt(JSON.stringify(secretDate), public_key).key,
  }
  UrlParams.data = encodeURIComponent(UrlParams.data)
  UrlParams.key = encodeURIComponent(UrlParams.key)
  return UrlParams
}

export default request
